package com.miplus.ccrm.core.service.cust;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.query.MPJLambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.*;
import com.miplus.ccrm.core.controller.vo.cust.ConSimplifyResVo;
import com.miplus.ccrm.core.controller.vo.cust.ContEditVo;
import com.miplus.ccrm.core.controller.vo.cust.ContReqVo;
import com.miplus.ccrm.core.controller.vo.cust.ContResVo;
import com.miplus.ccrm.core.mapper.FiCreditcasesMapper;
import com.miplus.ccrm.core.pojo.ConContact;
import com.miplus.ccrm.core.mapper.ConContactMapper;
import com.miplus.ccrm.core.pojo.FiCreditcases;
import com.miplus.ccrm.core.service.conf.SysNamesService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author pc
 * @description 针对表【con_contact(客户联系人表)】的数据库操作Service实现
 * @createDate 2024-03-30 09:55:28
 */
@Service
public class ConContactServiceImpl extends MPJBaseServiceImpl<ConContactMapper, ConContact>
        implements ConContactService{

    @Value("${aes.key}")
    private String aesKey;

    @Resource
    private SysNamesService sysNamesService;

    @Resource
    private FiCreditcasesMapper fiCreditcasesMapper;


    @Override
    public IPage<ContResVo> contactList(JSysUser user, ContReqVo paras)
    {
        String $usrid=user.getUsrid();

//        List<String> phntypelist=sysNamesService.getNamesID("CON.PHONETYP",false);
//        List<String> relationtypelist=sysNamesService.getNamesID("CON.RELATION",false);
//        List<String> originlist=sysNamesService.getNamesID("DATA.ORIGIN", JUsrPerm.hasPermission(user,JUsrPerm.VIEW_ALLORGIN));

        String relational=null;
//        if(JPubUtils.IsNotEmpty(paras.getCreditcaseid())){
//            FiCreditcases dbFiCreditcases = fiCreditcasesMapper.selectById(paras.getCreditcaseid());
//            if(dbFiCreditcases.getMthsDay()>0 && dbFiCreditcases.getMthsDay()<=3){
//                relational="0";
//            }
//        }
        if(JPubUtils.IsNotEmpty(paras.getMthsday())  && paras.getMthsday() <= 3)
        {
            relational="0";
        }
        else if(JPubUtils.IsNotEmpty(paras.getCreditcaseid())){
            FiCreditcases dbFiCreditcases = fiCreditcasesMapper.selectById(paras.getCreditcaseid());
            if(dbFiCreditcases.getMthsDay()>0 && dbFiCreditcases.getMthsDay()<=3){
                relational="0";
            }
        }
        boolean hasSecuPhnPermit = JUsrPerm.hasPermission(user,"disstar.phone");
        return selectJoinListPage(new Page<>(paras.getPageNum(), paras.getPageSize()),
                ContResVo.class,
                new MPJLambdaWrapper<ConContact>()
                        .selectAs("fun_getnames('CON.RELATION',t.relational)",ContResVo::getRelationaldsc)
                        .selectAs("fun_getnames('DATA.ORIGIN',t.origin)",ContResVo::getOrigindsc)
                        .selectAs("fun_getnames('CON.PHONETYP',t.phntype)",ContResVo::getPhntypedsc)
                        .selectAs("fi_hasStopCall(t.phone,'CALL')",ContResVo::getIsstopcall)
                        .selectAs("fi_hasStopCall(t.phone,'SMS')",ContResVo::getIsstopsms)
                        // .selectAs(String.format("fi_starSecu('%s','disstar.phone',t.phone,'')",$usrid),ContResVo::getPhone)
                        .selectAll(ConContact.class)
//                        .in(ConContact::getPhntype,phntypelist)
//                        .in(ConContact::getRelational,relationtypelist)
//                        .in(ConContact::getOrigin,originlist)
                        .eq("t.customernumber",paras.getCustomernumber())
                        .eq(JPubUtils.IsNotEmpty(relational),"t.relational",relational)
                        .eq(ConContact::getIsprimary,1)
                        .orderByAsc(ConContact::getRelational)
                        .orderByAsc(ConContact::getOrigin) // 上修30 催收系统 35 征信 40 其他：50
                        .orderByDesc(ConContact::getCreateddate)
        ).convert(x->{
            if(!hasSecuPhnPermit)
            {
                if(JPubUtils.IsNotEmpty(x.getPhone()) && x.getPhone().length() > 6 ){
                    String phn = x.getPhone().substring(0,3) + "***" + x.getPhone().substring(x.getPhone().length() -3);
                    x.setPhone(phn);

                }
                //改成创建神时间返回。
                x.setLastmodifieddate(x.getCreateddate());
            }
            return x;
        });
    }

    @Override
    public List<ConSimplifyResVo> contactSimplifyList(String customernumber) {

        return baseMapper.contactSimplifyList(customernumber);
    }


    @Override
    public ContResVo contactInfo(Long contactid)
    {
        return selectJoinOne(
                ContResVo.class,
                new MPJLambdaWrapper<ConContact>()
                        .selectAs("fun_getnames('CONTACTREL',t.relational)",ContResVo::getRelationaldsc)
                        .selectAs("fun_getnames('DATA.ORIGIN',t.origin)",ContResVo::getOrigindsc)
                        .selectAs("fun_getnames('CON.PHONETYP',t.phntype)",ContResVo::getPhntypedsc)
                        .selectAs("fi_hasStopCall(t.phone,'CALL')",ContResVo::getIsstopcall)
                        .selectAs("fi_hasStopCall(t.phone,'SMS')",ContResVo::getIsstopsms)
                        .selectAll(ConContact.class)
                        .eq("contactnumber",contactid)
        );
    }

    @Override
    public CmdResVo updateContact(String $usrid, ContEditVo paras)
    {
        ConContact def=new ConContact();
        BeanUtils.copyProperties(paras,def);
        String phn=paras.getPhone().trim();
        if(phn.indexOf("*")>=0){
            def.setPhone(null); //保持原号码
        }
        else{
            def.setPhone(JPubUtils.cleanPhoneNumber(phn));
        }
        def.setLastmodifiedby($usrid);
        def.setLastmodifieddate(new Date());

        if( isExistsSameContact(def.getContactnumber(),def.getCustomernumber(), def.getName(),
                def.getRelational(), def.getPhone()) == 1)
        {
            return new CmdResVo(-1,"该联系人电话已存在");
        }
        int ret=baseMapper.updateById(def);
        return new CmdResVo(ret,def.getContactnumber().toString());
    }
    private int isExistsSameContact(Integer contactNumber, String customernumber,String custName, String relational, String phn)
    {
        Long count =  selectJoinCount( new MPJLambdaWrapper<ConContact>()
                .ne(ObjectUtils.isNotNull(contactNumber),ConContact::getContactnumber,contactNumber)
                .eq(ConContact::getCustomernumber,customernumber)
                .eq(StringUtils.isNotEmpty(custName),ConContact::getName, custName)
                .eq(StringUtils.isNotEmpty(relational),ConContact::getRelational,relational)
                .eq(StringUtils.isNotEmpty(phn),ConContact::getPhone,phn)
                .eq(ConContact::getIsprimary,1)
        );
        if( count == 0L)
            return 0;
        else
            return 1;
    }
    @Override
    public CmdResVo insertContact(String $usrid,ContEditVo paras)
    {
        ConContact def=new ConContact();
        BeanUtils.copyProperties(paras,def);
        if(JPubUtils.IsEmpty(paras.getOrigin())) {
            def.setOrigin("35"); //系统自建
        }
        if(JPubUtils.IsEmpty(paras.getPhntype())) {
            def.setPhntype("01"); //本人电话。
        }
        def.setCreatedby($usrid);
        def.setCreateddate(new Date());
        def.setLastmodifiedby($usrid);
        def.setLastmodifieddate(new Date());

        def.setPhone(JPubUtils.cleanPhoneNumber(paras.getPhone()));
        def.setIsprimary(1);

        if( isExistsSameContact(null,def.getCustomernumber(), def.getName(),def.getRelational(),def.getPhone()) ==1)
        {
            return new CmdResVo(-1,"该联系人电话已存在");
        }
        int ret=baseMapper.insert(def);
        return new CmdResVo(ret,def.getContactnumber().toString());
    }

    @Override
    public CmdResVo deleteContact(String $usrid, Long contactid)
    {
        ConContact conContact = getById(contactid);
        if(!conContact.getCreatedby().equals($usrid))
            return new CmdResVo(-1,"无法删除");
        int ret=baseMapper.deleteById(contactid);
        return new CmdResVo(ret,Long.toString(contactid));
    }

    @Override
    public CmdResVo getSecuPhone(Long contactid)
    {
        ConContact contact=baseMapper.selectById(contactid);
        String phone=contact.getPhone();
        if(JPubUtils.IsEmpty(aesKey)){
            JPubUtils.PrintWarn("getSecuPhone","nofindaesKey");
        }
        phone=JSecurity.aesEncrypt(phone, aesKey);
        return new CmdResVo(1,phone);
    }

    @Override
    public String getPhone(Long contactid)
    {
        ConContact contact=baseMapper.selectById(contactid);
        return contact.getPhone();
    }
}




